﻿Imports TNValidate


Namespace AboutDNN.DNNMVC

    Public MustInherit Class BaseModel

        Private _validate As Validator

        Public MustOverride Sub ExecuteValidation()

        Protected Function Validate() As Validator
            If _validate Is Nothing Then _validate = New Validator
            Return _validate
        End Function

        Public Function IsValid() As Boolean
            Return IsValid(False)
        End Function

        Public Function IsValid(ByVal throwException As Boolean) As Boolean
            ExecuteValidation()
            Dim hasErrors = Validate.HasErrors
            IsValid = hasErrors
            If hasErrors AndAlso throwException Then
                Throw GetErrorsAsException()
            End If
        End Function

        Public Function GetErrors() As List(Of ModelError)
            ExecuteValidation()
            Dim errors = New List(Of ModelError)
            For Each er In _validate.ValidatorResults
                errors.Add(New ModelError(er.FieldName, er.ValidationMessage))
            Next
            Return errors
        End Function

        Public Function GetErrorsAsException() As Exception
            ExecuteValidation()
            Dim errors = GetErrors()
            Dim message As String = ""
            For Each er In errors
                If message.Length > 0 Then message += " | "
                message += er.Message
            Next
            Return New Exception(message)
        End Function

    End Class

End Namespace